<?php 
namespace App\Services\User;

use App\Facades\Infra\User\MessageManage;
use App\Facades\Services\User\UserService;
use EasyWeChat\Message\Text;
use App\Exceptions\WeChatException;
use App\Facades\Infra\User\DoctorManage;
use DB;
use App\Utils\SendMessage;

class MessageService{

	public function getOneSelfMessage(){
		$user = UserService::getUser();

		$conditions['wechat_user_id'] = $user->id;

		return MessageManage::getMessageAndReply($conditions)->get();

	}

	public function createMessage($data){

		$data['wechat_user_id'] = UserService::getUser()['id'];

		DB::transaction(function() use ($data){

			MessageManage::createMessage($data);

			$wechatDoctorInfoId = $data['wechat_doctor_info_id'];

			$toOpenId = $this->getDoctorOpenIdByDoctorInfoId($wechatDoctorInfoId);

			$message = "来自于".UserService::getUserInfo()['name']."的留言：".$data['content'];

			$this->sendMessageToWeChat($toOpenId,$message);
		});
		

		return;
	}

	public function createDoctorReply($data){

		$data['reply_type'] = 1;

		MessageManage::createReply($data);

		$conditions['id'] = $data['message_id'];

		$toOpenId = MessageManage::getUser($conditions)->wechatUser->openid;

		// dd($toOpenId);

		$message = "来自于医生的回复：".$data['reply_content'];

		$this->sendMessageToWeChat($toOpenId,$message);

		return;
	}

	public function createUserReply($data){
		
		$data['reply_type'] = 2;

		MessageManage::createReply($data);
		
		$conditions['id'] = $data['message_id'];

		$toOpenId = MessageManage::getDoctor($conditions)->wechatDoctorInfo->wechatDoctor->openid;

		$message = "来自于".UserService::getUserInfo()['name']."的回复：".$data['reply_content'];

		$this->sendMessageToWeChat($toOpenId,$message);

		return;
	}

	private function getDoctorOpenIdByDoctorInfoId($doctorInfoId){
		
		$conditions['id'] = $doctorInfoId;
		
		return DoctorManage::getDoctor($conditions)->first()->wechatDoctor->openid;
	}


	private function sendMessageToWeChat($toOpenId,$message){
		SendMessage::send($toOpenId,$message);
	}
}
